﻿using System;
using System.Text;
using K9Nano.Dependency;

namespace K9Nano.Serialize
{
    public class JsonSerializer : ISerializer, ISingletonDependency
    {
        public byte[] Serialize(object obj)
        {
            if (obj == null) return new byte[0];
            if (obj is byte[] bytes) return bytes;

            var text = SerializeToString(obj);
            return Encoding.UTF8.GetBytes(text);
        }

        public string SerializeToString(object obj)
        {
            return System.Text.Json.JsonSerializer.Serialize(obj);
        }

        public T Deserialize<T>(byte[] bytes)
        {
            if (bytes == null) throw new ArgumentNullException(nameof(bytes));
            if (typeof(T) == typeof(byte[]))
            {
                return (T) (object) bytes;
            }

            var text = Encoding.UTF8.GetString(bytes);

            var result = System.Text.Json.JsonSerializer.Deserialize<T>(text);

            return result;
        }

        public object Deserialize(string data, Type type)
        {
            var result = System.Text.Json.JsonSerializer.Deserialize(data, type);
            return result;
        }
    }
}